package io.renren.modules.demo.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.log.Log;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.demo.dto.BusLogisticsDTO;
import io.renren.modules.demo.excel.BusLogisticsExcel;
import io.renren.modules.demo.model.PrivateChatMsg;
import io.renren.modules.demo.model.ReceiveChatMsg;
import io.renren.modules.demo.service.BusLogisticsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 物流信息管理
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-04-28
 */
@RestController
@RequestMapping("wcfhttp/callback")
@Api(tags = "微信消息")
@Slf4j
public class WcfHttpController {
    @Autowired
    private BusLogisticsService busLogisticsService;
    @Value("${wcf.url}")
    private String wcfUrl;
    @Value("${wcf.urlV2}")
    private String urlV2;
    @Value("${wcf.roomid}")
    private String roomids;

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("demo:buslogistics:info")
    public Result<BusLogisticsDTO> get(@PathVariable("id") Long id) {
        BusLogisticsDTO data = busLogisticsService.get(id);

        return new Result<BusLogisticsDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("callback")
    @LogOperation("接收到消息")
//    @RequiresPermissions("demo:buslogistics:save")
    public Result save(@RequestBody ReceiveChatMsg dto, HttpServletRequest request) {
        //效验数据
        log.info("msg:{}", dto);
        final Boolean isGroup = dto.getIs_group();
        log.info("isGroup:{}", isGroup);
        log.info("sign:{}", dto.getSign());
        final String sender = dto.getSender();
        log.info("sender:{}", sender);
        final String roomid = dto.getRoomid();
        log.info("roomid:{}", roomid);
        final String content = dto.getContent();
        log.info("content:{}", content);
//        log.info("request:{}",request);
//        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
//        busLogisticsService.save(dto);
//        {
//  "aters": "wxid_88888888888888", 要@的人列表，逗号分隔
//  "msg": "换行用\n就可以了\n @昵称随便写", 要发送的消息内容
//  "receiver": "88888888888@chatroom" 消息接收人，当为群时可@
//}
        if (roomids.contains(roomid) && (StrUtil.removeSuffix(content, "公司").length()<content.length())) {
            log.info("回复消息:{}", roomid);
            Map<String, Object> params = new HashMap<>();
            params.put("name", content);
            List<BusLogisticsDTO> list = busLogisticsService.list(params);
            log.info("list.size(){}", list.size());
            if (list.size() > 0) {
//                wcf 3.0.10
                new Thread(() -> {
                    try {
                        Thread.sleep(500);
                        final String s = content + "快递单号\n" + parseListToStr2(list);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.set("aters", "");
                        jsonObject.set("msg", s);
                        jsonObject.set("receiver", roomid);
                        HttpUtil.post(wcfUrl, jsonObject.toString());
                    } catch (Exception e) {
                        log.info("{}：发送失败",wcfUrl);
//                        throw new RuntimeException(e);
                    }
                }).start();
//                wcf 3.0.14
//                {
//                    "aters": "wxid_88888888888888",
//                        "msg": "换行用\n就可以了\n @昵称随便写",
//                        "receiver": "88888888888@chatroom"
//                }
                new Thread(() -> {
                    try {
                        Thread.sleep(500);
                        final String s = content + "快递单号\n" + parseListToStr2(list);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.set("aters", "");
                        jsonObject.set("msg", s);
                        jsonObject.set("receiver", roomid);
                        HttpUtil.post(urlV2, jsonObject.toString());
                    } catch (Exception e) {

//                        throw new RuntimeException(e);
                    }
                }).start();
            }else{
                new Thread(() -> {
                    try {
                        Thread.sleep(500);
                        final String s = content + "快递单号\n"+"加急制作中，请稍后查询";
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.set("aters", "");
                        jsonObject.set("msg", s);
                        jsonObject.set("receiver", roomid);
                        HttpUtil.post(wcfUrl, jsonObject.toString());
                    } catch (Exception e) {
                        log.info("{}：发送失败",urlV2);
//                        throw new RuntimeException(e);
                    }
                }).start();
                new Thread(() -> {
                    try {
                        Thread.sleep(500);
                        final String s = content + "快递单号\n" +"加急制作中，请稍后查询" ;
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.set("aters", "");
                        jsonObject.set("msg", s);
                        jsonObject.set("receiver", roomid);
                        HttpUtil.post(urlV2, jsonObject.toString());
                    } catch (Exception e) {
                        log.info("{}：发送失败",urlV2);
//                        throw new RuntimeException(e);
                    }
                }).start();
            }
        }
        return new Result();
    }

    public static <T> String parseListToStr2(List<BusLogisticsDTO> list) {
        StringBuffer sb = new StringBuffer();
        list.stream().forEach(str -> {
            sb.append("#" + str.getLogisticsNumber()).append("\n");
        });
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

}